<template>
  <div class="form-single-fragment" style="position: relative;">
    <h3>{{item_title}}</h3>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" size="mini" label-position="right">
      <el-row :gutter="20" class="form-single-info">
        <el-col :span="16">
          <el-col :span="8">
            <el-form-item label="考勤组" prop="groupName">
              <el-input class="input-item" v-model="ruleForm.groupName" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="考勤人员" prop="listUser">
              <el-select v-model="selectUser" multiple collapse-tags filterable placeholder="请选择"
                @change="selectlistUser">
                <el-option v-for="item in listUsers" :key="item.userId"
                :label="item.userName" :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="无需考勤人员">
              <el-select v-model="selectExclude" multiple collapse-tags filterable placeholder="请选择"
                @change="selectlistExcludeUser">
                <el-option v-for="item in listExcludeUser" :key="item.userId"
                :label="item.userName" :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <h4>考勤时间</h4>
            <el-row :gutter="20" class="el-form-info">
              <el-col :span="24">
                <el-form-item label="工作日" prop="groupWeek">
                  <el-checkbox-group v-model="groupWeek" @change="selectgroupWeek">
                    <el-checkbox label="1">周一</el-checkbox>
                    <el-checkbox label="2">周二</el-checkbox>
                    <el-checkbox label="3">周三</el-checkbox>
                    <el-checkbox label="4">周四</el-checkbox>
                    <el-checkbox label="5">周五</el-checkbox>
                    <el-checkbox label="6">周六</el-checkbox>
                    <el-checkbox label="7">周日</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="上班时间" prop="clockInTime">
                  <el-time-picker v-model="ruleForm.clockInTime" placeholder="上班时间"
                    format="HH:mm" value-format="HH:mm">
                  </el-time-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="下班时间" prop="clockOutTime">
                  <el-time-picker v-model="ruleForm.clockOutTime" placeholder="下班时间"
                    format="HH:mm" value-format="HH:mm">
                  </el-time-picker>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="午休时间">
                  <el-time-picker is-range v-model="noonClock" range-separator="至"
                    format="HH:mm" value-format="HH:mm" @change="selectnoonClock"
                    start-placeholder="开始时间" end-placeholder="结束时间" placeholder="午休时间">
                  </el-time-picker>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="特殊时间">
                  <div>
                    <el-button size="mini" @click="selectTime()">添加</el-button>
                    <strong>不用打卡日期</strong>
                    <el-checkbox v-model="checked" @change="selectlistHoliday">同步法定节假日</el-checkbox>
                  </div>
                  <div class="table_container">
                    <el-table :data="ruleForm.listExcludeDate" size="mini" style="width: 100%;" header-cell-class-name="table-header-gray">
                    <el-table-column prop="excludeDate" align="center" label="日期"></el-table-column>
                    <el-table-column prop="excludeReason" align="center" label="考勤类型"></el-table-column>
                    <el-table-column prop="remarks" align="center" label="备注"></el-table-column>
                    <el-table-column label="操作" align="center" width="80">
                      <template slot-scope="scope">
                        <el-button type="text" @click="deleteTime(scope.$index)">删除</el-button>
                      </template>
                    </el-table-column>
                    </el-table>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="24">
            <h4>打卡方式</h4>
            <el-row :gutter="20" class="el-form-info">
              <el-col :span="24">
                <el-form-item label="考勤地点" prop="listPosition">
                  <div>
                    <el-button size="mini" @click="getmapannotation()">添加</el-button>
                  </div>
                  <div class="table_container">
                    <el-table :data="ruleForm.listPosition" size="mini" style="width: 100%;" header-cell-class-name="table-header-gray">
                    <el-table-column prop="positionName" align="center" label="地址名称" :show-overflow-tooltip="true"></el-table-column>
                    <el-table-column prop="detailAddr" align="center" label="详细地址" :show-overflow-tooltip="true"></el-table-column>
                    <el-table-column label="操作" align="center" width="80">
                      <template slot-scope="scope">
                        <el-button type="text" @click="deleteAddress(scope.$index)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-form-item>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="打卡范围" prop="positionRange">
                      <el-select v-model="ruleForm.positionRange" placeholder="请选择">
                        <el-option label="100米" value="100"></el-option>
                        <el-option label="300米" value="300"></el-option>
                        <el-option label="500米" value="500"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="外勤打卡">
                  <el-radio-group v-model="ruleForm.fieldPunchIn">
                    <el-radio :label="1">允许</el-radio>
                    <el-radio :label="-1">不允许</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item style="padding: 20px 0;">
              <el-button size="mini" @click="resetForm()">取消</el-button>
              <el-button type="primary" size="mini" @click="submitForm()">保存</el-button>
            </el-form-item>
          </el-col>
        </el-col>
      </el-row>
    </el-form>
    <div class="annotation" v-if="selectDaybox">
      <selectDay ref="selectDay" @getTime="getTime" v-model="selectDaybox"></selectDay>
    </div>
    <div class="annotation" v-if="mapannotationbox">
      <mapannotation ref="mapannotation" @getLocation="getLocation" v-model="mapannotationbox"></mapannotation>
    </div>
  </div>
</template>

<script>
import selectDay from '@/components/selector/selectDay.vue'
import mapannotation from '@/components/selector/mapannotation.vue'
import { AttendanceSettings } from '@/api/attenDances.js';
export default {
  name: 'addAttendance',
  components: { selectDay, mapannotation },
  data () {
    return {
      item_title: '新增考勤组',
      isShowloading: false,
      selectDaybox: false,
      mapannotationbox: false,
      userId: null,
      userNamelist: [],
      listUsers: [],
      selectUser: [],
      listExcludeUser: [],
      selectExclude: [],
      noonClock: '',
      checkList: [],
      checked: false,
      radio: '允许',
      groupWeek: [],
      upResId: null,
      upResName: null,
      ruleForm: {
        groupName: '',
        clockInTime: '',
        clockOutTime: '',
        fieldPunchIn: 1,
        positionRange: '',
        groupWeek: '',
        listUser: [],
        listExcludeUser: [],
        listExcludeDate: [],
        listPosition: [],
        noonClockInTime: '',
        noonClockOutTime: ''
      },
      rules: {
        groupName: [{ required: true, message: '请输入', trigger: 'blur' }],
        groupWeek: [{ required: true, message: '请选择', trigger: 'change' }],
        clockInTime: [{ required: true, message: '请选择', trigger: 'change' }],
        clockOutTime: [{ required: true, message: '请选择', trigger: 'change' }],
        positionRange: [{ required: true, message: '请选择', trigger: 'change' }],
        listPosition: [{ required: true, message: '请添加', trigger: 'blur' }],
        listUser: [{ required: true, message: '请选择', trigger: 'blur' }]
      }
    };
  },
  mounted () {
    this.listGroupUser()
    if (this.$route.query.groupId) {
      this.loadAttendancedetail()
      this.item_title = '编辑考勤组'
    } else {
      this.item_title = '新增考勤组'
    }
  },
  methods: {
    /**
     * 考勤组详情
     */
    loadAttendancedetail () {
      let params = this.$route.query.groupId
      return new Promise((resolve, reject) => {
        AttendanceSettings.detail(this, params).then(res => {
          this.ruleForm = res.data
          this.groupWeek = res.data.groupWeek.split(',')
          this.noonClock = []
          this.noonClock.push(this.ruleForm.noonClockOutTime, this.ruleForm.noonClockInTime)
          if (!res.data.listUser) {
            this.ruleForm.listUser = []
          } else {
            this.selectUser = []
            let listUserinfo = res.data.listUser
            listUserinfo.forEach(item => {
              this.selectUser.push(item.userId)
              this.listUsers.push(item)
            })
            this.selectlistUser(this.selectUser)
          }
          if (!res.data.listExcludeUser) {
            this.ruleForm.listExcludeUser = []
          } else {
            this.selectExclude = []
            let listExcludeUserinfo = res.data.listExcludeUser
            listExcludeUserinfo.forEach(items => {
              this.selectExclude.push(items.userId)
            })
            this.selectlistExcludeUser(this.selectExclude)
          }
          if (!res.data.listExcludeDate) {
            this.ruleForm.listExcludeDate = []
          }
          if (!res.data.listPosition) {
            this.ruleForm.listPosition = []
          }
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 考勤人员列表
     */
    listGroupUser () {
      return new Promise((resolve, reject) => {
        AttendanceSettings.listGroupUser(this).then(res => {
          this.listUsers = res.data
          this.listExcludeUser = res.data
          this.userNamelist = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 考勤人员选择
     */
    selectlistUser (data) {
      let listExcludeUsernew = []
      this.userNamelist.forEach((item, index) => {
        let ExcludeUser = data.find((items) => {
          return item.userId === items
        })
        if (!ExcludeUser) {
          listExcludeUsernew.push(item)
        }
      })
      this.listExcludeUser = listExcludeUsernew
      let listUsernew = []
      data.forEach((User, index) => {
        let Obj = {}
        Obj.userId = User
        listUsernew.push(Obj)
      })
      this.ruleForm.listUser = listUsernew
    },
    /**
     * 无需考勤人员选择
     */
    selectlistExcludeUser (data) {
      let listUsernew = []
      this.userNamelist.forEach((item, index) => {
        let ExcludeUser = data.find((items) => {
          return item.userId === items
        })
        if (!ExcludeUser) {
          listUsernew.push(item)
        }
      })
      this.listUsers = listUsernew
      let listExcludeUsernew = []
      data.forEach((Exclude, index) => {
        let Obj = {}
        Obj.userId = Exclude
        listExcludeUsernew.push(Obj)
      })
      this.ruleForm.listExcludeUser = listExcludeUsernew
    },
    /**
     * 工作日选择
     */
    selectgroupWeek (data) {
      this.ruleForm.groupWeek = data.join(',')
    },
    /**
     * 午休时间选择
     */
    selectnoonClock (noonClock) {
      if (noonClock) {
        this.ruleForm.noonClockOutTime = noonClock[0]
        this.ruleForm.noonClockInTime = noonClock[1]
      } else {
        this.ruleForm.noonClockOutTime = ''
        this.ruleForm.noonClockInTime = ''
      }
    },
    /**
     * 同步法定节假日
     */
    selectlistHoliday (data) {
      let params = {
        groupId: this.ruleForm.groupId,
        userId: this.ruleForm.userId
      }
      if (data) {
        return new Promise((resolve, reject) => {
          AttendanceSettings.listHoliday(this, params).then(res => {
            res.data.forEach(item => {
              let info = this.ruleForm.listExcludeDate.find(items => {
                return item.holidayDate === items.excludeDate
              })
              if (!info) {
                let Obj = {
                  excludeDate: item.holidayDate.substring(0, 10),
                  remarks: item.holidayName,
                  excludeReason: item.holiday ? '休息' : '上班'
                }
                this.ruleForm.listExcludeDate.push(Obj)
              }
            })
          }).catch(e => {
            reject(e);
          });
        });
      }
    },
    /**
     * 不用打卡日期选择
     */
    selectTime () {
      this.selectDaybox = true
      this.$nextTick(() => {
        this.$refs.selectDay.info()
      })
    },
    /**
     * 不用打卡日期添加
     */
    getTime (data) {
      let Obj = {
        excludeDate: data.time,
        excludeReason: data.excludeReason,
        remarks: data.remarks
      }
      this.ruleForm.listExcludeDate.push(Obj)
    },
    /**
     * 不用打卡日期删除
     */
    deleteTime (index) {
      this.ruleForm.listExcludeDate.splice(index, 1)
    },
    /**
     * 考勤地点删除
     */
    deleteAddress (index) {
      this.ruleForm.listPosition.splice(index, 1)
    },
    /**
     * 考勤地点选择
     */
    getmapannotation () {
      this.mapannotationbox = true
      this.$nextTick(() => {
        this.$refs.mapannotation.info()
      })
    },
    /**
     * 考勤地点添加
     */
    getLocation (data) {
      let Obj = {}
      Obj.positionName = data.address
      Obj.detailAddr = data.addressComponents.province + data.addressComponents.city + data.addressComponents.district + data.addressComponents.street + data.addressComponents.streetNumber
      Obj.positionLon = data.lng
      Obj.positionLat = data.lat
      this.ruleForm.listPosition.push(Obj)
    },
    /**
     * 提交表单
     */
    submitForm () {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.isShowloading = true;
          let params = this.ruleForm;
          if (params.groupId) { // 修改
            return new Promise((resolve, reject) => {
              AttendanceSettings.update(this, params).then(res => {
                this.$message({
                  showClose: true,
                  message: '修改成功！',
                  type: 'success'
                });
                this.resetForm()
              }).catch(e => {
                reject(e);
              });
            });
          } else { // 添加
            return new Promise((resolve, reject) => {
              AttendanceSettings.add(this, params).then(res => {
                this.$message({
                  showClose: true,
                  message: '添加成功！',
                  type: 'success'
                });
                this.resetForm()
              }).catch(e => {
                reject(e);
              });
            });
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm () {
      this.$router.go(-1)
    }
  }
}
</script>

<style scoped>
h3{border-bottom: 1px solid #E9E9EB;padding: 0 0 10px;}
.table_container{margin: 10px 0;}
.form-single-info{display: flex;justify-content: center;}
.el-form-info{box-shadow: 0 0 10px rgba(0,0,0,0.05);padding: 20px;}
.el-form-info strong{margin: 0 10px;}
.el-form-info .el-time-picker{width: 100% !important;}
</style>
